import { formatDate } from '@/utils/filters'
import { getLocalStorage, setLocalStorage } from '@/utils/localStore'
import { defineStore } from 'pinia'
import { IMessage } from './type'

export type MessageState = {
    messageList: Array<IMessage>
}

export const messageStore = defineStore('messageStore', {
    state: (): MessageState => {
        return {
            messageList: []
        }
    },
    actions: {
        addMessage(msg: IMessage) {
            this.messageList.push(msg)
            setLocalStorage('messages', JSON.stringify(this.messageList))
        }
    },
    getters: {
        getMessages(state) {
            if (state.messageList.length <= 0) {
                let messages = getLocalStorage('messages') || ''
                if (messages) {
                    this.messageList = JSON.parse(messages)
                    this.messageList.forEach((item: IMessage) => {
                        item.send_time_text = formatDate(item.send_time)
                    })
                }
            }

            return state.messageList
        }
    }
})
